<template>
<div class="containerWrap">
  <el-container class="container">
    <el-aside class="appTree" width="200px">
      <app-tree v-bind:tree-data="treeData" :title="treeName"
                v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main class="rightMain">
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              字典名称：<el-input size="small" placeholder="请输入字典名称" v-model="queryData.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button size="small" @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main class="tableMain">
          <app-table :page-data="pageData"
                     :table-columns="tableColumns"
                     v-on:currentChange="handleCurrentChange"
                     v-on:handleCheckedRows="handleCheckedRows" />
        </el-main>
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible"  :close-on-click-modal="false" :before-close="close" class="dialog_style">
          <div class="formWrapper">
            <el-form class="formMain" :model="formData"
                    :rules="rules"
                    ref="formData"
                    label-width="110px"
                    size="small">
              <el-divider content-position="left">基本信息</el-divider>
              <el-row :gutter="15">
                <el-col :span="12">
                  <el-form-item label="字典分类：" prop="dictionaryTypeId">
                     <el-select filterable style="width:100%" v-model="formData.dictionaryTypeId" placeholder="字典分类">
                      <el-option v-for="(item, index) in treeData" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="字典值名称：" prop="name">
                    <el-input v-model="formData.name" placeholder="字典值名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="字典值：" prop="value">
                    <el-input v-model="formData.value" type="textarea" :rows="2" placeholder="字典值"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button size="small" @click="cancel('formData')">取 消</el-button>
              <el-button size="small" type="primary" :disabled="showOnly" @click="save('formData')">提 交</el-button>
            </div>
          </div>
        </el-dialog>
      </el-container>
    </el-main>
  </el-container>
</div>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import { createDictionItem, findDictionItem, updateDictionItem, deleteDictionItem } from '@/http/setApi'
import { findDictionaryList, allDict } from '@/http/AppApi'
import {setDictInfo} from '@/utils/LocalDataUtil'
export default {
  data () {
    return {
      active: 1,
      mapMode: 'full',
      treeName: '字典分类',
      dialogTitle: '新增字典集',
      currentSelectedRowId: '',
      showMap: false,
      showOnly: false,
      dialogFormPromise: false,
      dialogFormVisible: false,
      treeData: [],
      currentSelectedData: [],
      formData: {},
      pageData: {},
      queryData: {},
      mapTarget: {},
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      tableColumns: [
        { label: '字典名称', prop: 'name' },
        { label: '字典值', prop: 'value' },
        { label: '类别名称', prop: 'dictionaryTypeId', formatter: this.typeFormatter }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      rules: {
        dictionaryTypeId: [{
          required: true,
          message: '字典类别',
          trigger: 'change'
        }],
        name: [{
          required: true,
          message: '填写字典值名称',
          trigger: 'blur'
        }],
        value: [{
          required: true,
          message: '填写字典值',
          trigger: 'blur'
        }]

      }
    }
  },
  created () {},
  mounted () {
    this.getDictionaryTree()
  },
  components: {BtnGroup, AppTable, AppTree},
  methods: {
    typeFormatter (row) {
      let options = this.treeOption
      for (let i = 0; i < options.length; i++) {
        const element = options[i]
        if (element.id === row.dictionaryTypeId) {
          return element.name
        }
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.beforeSubmit()
          if (this.formData.id) {
            updateDictionItem(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.loadDictData()
                this.cancel(formName)
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: resp.data
                })
              }
            })
          } else {
            createDictionItem(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.loadDictData()
                this.cancel(formName)
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
              } else {
                this.$message({
                  type: 'success',
                  message: resp.data
                })
              }
            })
          }
        }
      })
    },
    beforeSubmit () {
      console.log(this.formData.allIdArr)
      if (this.formData.allIdArr && this.formData.allIdArr.length > 0) {
        let allId = this.formData.allIdArr.join(',')
        this.$set(this.formData, 'allId', allId)
        let unitId = this.formData.allIdArr[this.formData.allIdArr.length - 1]
        this.$set(this.formData, 'unitId', unitId)
      }
      return true
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteDictionItem(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({type: 'success', message: '删除成功'})
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    getTableData () {
      let param = this.queryData
      findDictionItem(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    getDictionaryTree () {
      findDictionaryList().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          this.treeData = this.treeOption = data
          this.getTableData()
        }
      })
    },
    treeClickHandle (data) {
      console.log(data)
      this.queryData = {}
      this.queryData.dictionaryTypeId = data.id
      this.$set(this.formData, 'dictionaryTypeId', data.id)
      this.$set(this.formData, 'dictionaryTypeIdArr', data.id)
      this.getTableData()
    },
    btnClickCallback (callbackData) {
      this.dialogFormVisible = true
      this.showOnly = callbackData.showOnly
      this.dialogTitle = callbackData.dialogTitle
      console.log(callbackData)
      if (callbackData.btnType === 'post') {
        this.formData = this.formData.dictionaryTypeIdArr ? this.formData : {}
      } else if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
        console.log(this.formData)
        this.currentSelectedRowId = rows[0].id
      } else {
        this.currentSelectedData = []
      }
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    close (type) {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs['formData'].resetFields()
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs['formData'].resetFields()
    },
    loadDictData () {
      allDict().then(resp => {
        if (resp.code && resp.code === '200') {
          setDictInfo(resp.data)
          return false
        }
      })
    }
  }
}
</script>
<style scoped>
  .containerWrap {
    padding:10px;
    height: 100%;
    box-sizing: border-box
  }
  .container {
    height: 100%;
  }
</style>
